package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    // 今日佳人
    public ResponseEntity findTodayBest() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询缘分值最高用户
        RecommendUser recommendUser = recommendUserService.findMaxScoreRecommendUser(userId);
        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findUserInfoById(recommendUser.getUserId())); // 用户信息
        vo.setFateValue(recommendUser.getScore().longValue()); // 缘分值
        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 推荐用户
    public ResponseEntity findRecommendUserList(Integer pageNum, Integer pageSize) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询推荐分页
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, pageNum, pageSize);
        // 3.封装vo
        // 3.1 获取recommentUserList
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3.2 声明voList
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3.3 遍历recommentUserList
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                // userInfo
                vo.setUserInfo(userInfoService.findUserInfoById(recommendUser.getUserId()));
                // 缘分值
                vo.setFateValue(recommendUser.getScore().longValue());
                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将vo设置到pageBeanVo
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 用户详情封面
    public ResponseEntity findRecommendDetailHead(Long jiarenId) {
        // 1.获取线程内userId
        Long toUserId = UserHolder.get().getId();

        // 判断
        RecommendUser recommendUser = null;
        if (jiarenId == toUserId) {  // 个人动态
            recommendUser = new RecommendUser();
            recommendUser.setUserId(jiarenId);
            recommendUser.setScore(100d);
        } else { // 佳人动态
            // 2.调用rpc查询
            recommendUser = recommendUserService.findRecommendUserByCondition(toUserId, jiarenId);
        }

        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfoService.findUserInfoById(jiarenId));
        vo.setFateValue(recommendUser.getScore().longValue());
        // 4.返回
        return ResponseEntity.ok(vo);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private VisitorService visitorService;

    // 历史访客
    public ResponseEntity findVisitors() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.从redis中取出上次登录时间
        String lastLoginTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        List<Visitor> visitorList = null;
        // 3.查询历史访客
        if (StrUtil.isNotEmpty(lastLoginTime)) {
            visitorList = visitorService.findeAccessUser(userId, Long.parseLong(lastLoginTime));
        } else {
            visitorList = visitorService.findeAccessUser(userId, Long.parseLong("0"));
        }
        // 4.封装vo
        // 4.1 声明 voList
        List<VisitorVo> voList = new ArrayList<>();
        // 4.2 遍历 visitorList
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                // 创建vo
                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfoService.findUserInfoById(visitor.getVisitorUserId())); // 访问用户信息
                // 设置二人的缘分值
                RecommendUser recommendUser = recommendUserService.findRecommendUserByCondition(userId, visitor.getVisitorUserId());
                if (recommendUser != null) {
                    vo.setFateValue(recommendUser.getScore().longValue());
                } else {
                    vo.setFateValue(0l);
                }
                // 添加到voList
                voList.add(vo);
            }
        }
        // 5.记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 6.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserLocationService userLocationService;

    // 上传地址位置
    public void uploadLocation(Double longitude, Double latitude, String addrStr) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存地理位置
        userLocationService.saveUserLocation(longitude, latitude, addrStr, userId);
    }

    // 搜附近
    public ResponseEntity searchNearUser(String gender, Long distance) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);
        // 3.封装nearUserVo
        // 3.1 声明voList
        List<NearUserVo> voList = new ArrayList<>();
        // 3.2 遍历nearUserIdList
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {

                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 查询userInfo
                UserInfo userInfo = userInfoService.findUserInfoById(nearUserId);
                // 排除异性
                if (!userInfo.getGender().equals(gender)) {
                    continue;
                }

                // 创建vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                // vo添加到集合
                voList.add(vo);
            }
        }

        // 4.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private QuestionService questionService;

    public ResponseEntity strangerQuestions(Long jiarenId) {
        // 1.查询佳人的陌生人问题
        Question question = questionService.findByUserId(jiarenId);
        // 2.处理默认值
        if (question == null) {
            question = new Question();
        }
        // 3.返回问题
        return ResponseEntity.ok(question.getStrangerQuestion());

    }
}
